package com.hospital.tts.sax;

import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.hospital.tts.dataBean.Person;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class SAXForHandler extends DefaultHandler {
    private static final String TAG = "SAXForHandler";
    private List<Person> persons;
    private String perTag; // record the name of previous tag
    Person person;// current person

    public List<Person> getPersons() {
        return persons;
    }

    /**
     * 在开始解析文档时执行一次
     */
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        persons = new ArrayList<Person>();
        Log.e(TAG, "****startDocument()****");
    }

    @Override
    public void endDocument() throws SAXException {
        Log.e(TAG, "****endDocument()****");
    }

    /**
     * uri:命名空间
     * localName:标签名称
     * qName：带 命名空间的标签名
     * attributes：存放该标签的所有属性
     */
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {

        LogUtils.e(localName);
//        LogUtils.e("qName",qName);
//        LogUtils.e("attributes",attributes);
        if ("person".equals(localName)) {
            LogUtils.e(attributes.getLength());
            for (int i = 0; i < attributes.getLength(); i++) {
                Log.i(TAG, "attributeName:" + attributes.getLocalName(i) + ",attribute_value" + attributes.getValue(i));
                person = new Person();
                person.setId(Integer.valueOf(attributes.getValue(i)));
            }
        }
        perTag = localName;
        Log.i(TAG, qName + "****startElement()****");

    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        Log.e(TAG, "qName" + "***endElement()***");
        if ("person".equals(localName)) {
            persons.add(person);
            person = null;
        }
        perTag = null;
    }

    /**
     * ch:当前读取到的TextNode节点
     * start：字节开始的位置，如果要读取全部，那就是从0开始
     * length：当前TextNode的长度
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String data = new String(ch, start, length).trim();
        if (!"".equals(data)) {
            Log.i(TAG, "content" + data);
        }
        if ("name".equals(perTag)) {
            person.setName(data);
        } else if ("age".equals(perTag)) {
            person.setAge(new Short(data));
        }
    }

}
